import { SearchOutlined } from "@ant-design/icons";
import { Button, Card, Input, Modal, Pagination, Radio, Space } from "antd";

import Avatar from "@/assets/avatar.svg";
import Banner1 from "@/assets/banner-1.png";
import ZhongLogo from "@/assets/zhongchuanghui-logo.png";

import {
  BusinessCategoryDetailinfo,
  UsersubjectGtsubject,
  UsersubjectGtsubjectItem,
} from "@/api";
import { UserinfoEntrysone } from "@/api/user";
import IconLogOut from "@/assets/icon_exit.svg";
import IconPassWord from "@/assets/icon_password.svg";
import { useRef, useState } from "react";
import { history, useQuery } from "umi";

export default function HomePage() {
  const searchRef = useRef<any>();

  const [tag, setTag] = useState<number | undefined>();
  const [pageNum, setPageNum] = useState<number>(1);
  const [keyWord, setKeyword] = useState<string>();
  const { data: dataTags } = useQuery(["get/tags"], BusinessCategoryDetailinfo);

  const { data } = useQuery({
    refetchOnWindowFocus: false,
    queryKey: ["get/subject", pageNum, keyWord, tag],
    queryFn: () =>
      UsersubjectGtsubject({
        page: pageNum,
        limit: 9,
        appname: keyWord,
        item: tag,
      }),
  });

  const { data: userData } = useQuery({
    queryKey: ["get/user/info"],
    queryFn: UserinfoEntrysone,
  });

  function jumpTo(record: UsersubjectGtsubjectItem) {
    if (record.code.toString().startsWith("2")) {
      Modal.warn({
        title: "提示",
        content: "请联系园区管理员",
        okText: "知道了",
      });
      return;
    }

    window.open(renderUrlWithToken(record.home));
  }

  function renderUrlWithToken(url: string) {
    try {
      const u = new URL(url);
      u.searchParams.append("token", localStorage.getItem("token")!);
      return u.toString();
    } catch (error) {
      return url;
    }
  }

  return (
    <section className="flex relative overflow-hidden w-full">
      <div className=" flex-1 p-6">
        <div className="bg-white px-4 py-2 mb-8 rounded-lg">
          <img src={ZhongLogo} className=" block h-12" alt="" />
        </div>

        <div className="mb-4">
          <Radio.Group value={tag}>
            <Radio.Button value={undefined} onClick={() => setTag(undefined)}>
              全部
            </Radio.Button>
            {dataTags?.map((item, index) => (
              <Radio.Button
                key={item.bcid}
                value={item.bcid}
                onClick={() => setTag(item.bcid)}
              >
                {item.bcname}
              </Radio.Button>
            ))}
          </Radio.Group>
        </div>
        <div className=" grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
          {data?.data?.map((item) => (
            <>
              <Card
                key={item.code}
                bodyStyle={{
                  padding: 0,
                }}
              >
                <a onClick={() => jumpTo(item)} target="_blank">
                  <img
                    width="100%"
                    className=" block aspect-video w-fulli object-cover"
                    src={item.workimg}
                  />
                </a>
                <div className=" p-4">
                  <a
                    onClick={() => jumpTo(item)}
                    target="_blank"
                    className=" font-bold text-lg text-black mt-0"
                  >
                    {item.name}
                  </a>
                  <p>{item.details}</p>
                </div>
              </Card>
            </>
          ))}
        </div>
        {data?.data && data.data.length > 1 && (
          <Pagination
            onChange={setPageNum}
            current={pageNum}
            total={data?.total}
            className=" text-right mt-4"
          />
        )}
      </div>
      <div className=" w-[400px] bg-white py-12 px-6 relative">
        <Space.Compact style={{ width: "100%" }} size="large">
          <Input
            placeholder="请输入关键词搜索"
            prefix={<SearchOutlined />}
            ref={searchRef}
            onPressEnter={() => setKeyword(searchRef.current.input.value)}
          />
          <Button
            type="primary"
            onClick={() => {
              setKeyword(searchRef.current.input.value);
            }}
          >
            搜索
          </Button>
        </Space.Compact>

        <div className="flex items-start mt-12">
          <div>
            <p className=" text-gray-400 text-base m-0">你好</p>
            <h1 className="mb-0 text-3xl font-bold mt-2 text-black">
              {userData?.uname}
            </h1>
            <p className="text-gray-400 mt-2 mb-0">
              睿湖软件提供更加丰富的操作体验，壹贰叁肆备份
            </p>
          </div>

          <img
            src={Avatar}
            className=" w-20 h-20 block rounded-full ml-12"
            alt=""
          />
        </div>

        <div
          className=" mt-12 cursor-pointer"
          onClick={() => {
            Modal.warn({
              title: "提示",
              content: "请联系园区管理员",
              okText: "知道了",
            });
          }}
        >
          <img src={Banner1} className=" block w-full h-auto" alt="" />
        </div>
        <h3 className=" text-2xl font-bold text-black mt-12">个人中心</h3>
        <div
          className="flex items-center text-base mb-4 cursor-pointer hover:opacity-75"
          onClick={() => {
            Modal.warn({
              title: "提示",
              content: "修改密码请联系管理员",
              okText: "知道了",
            });
          }}
        >
          <i
            className=" w-16 h-16 bg-cover block mr-2"
            style={{
              backgroundImage: `url(${IconPassWord})`,
            }}
          />
          修改密码
        </div>
        <div
          className="flex items-center text-base mb-4 cursor-pointer hover:opacity-75"
          onClick={() => {
            history.replace("/login");
          }}
        >
          <i
            className=" w-16 h-16 bg-cover block mr-2"
            style={{
              backgroundImage: `url(${IconLogOut})`,
            }}
          />
          退出登录
        </div>

        <p className=" absolute bottom-2 left-0 right-0 text-xs text-gray-400 text-center">
          由XXXX提供技术支持
        </p>
      </div>
    </section>
  );
}
